#include "MapToolSelectRctangle.h"
#include "RubberBand.h"
#include "MapCanvas.h"
#include "Cursors.h"
#include "MapControlConfig.h"
#include <TGS/MapControl2.0/MapToPixel.h>
#include <TGS/GeoMath2.0/Point.h>
#include <TGS/GeoMath2.0/Polygon.h>
#include <QMouseEvent>
#include <QRect>

using namespace TGS::GeoMath;;


namespace TGS{
namespace MapControl{


MapToolSelectRectangle::MapToolSelectRectangle(MapCanvas* canvas )
    : MapTool( canvas ),
	_dragging( false )
{
	QPixmap mySelectQPixmap = QPixmap(( const char ** ) select_cursor );
	setCursor(QCursor( mySelectQPixmap, 1, 1 ));
	_rubberBand = nullptr;
}


void MapToolSelectRectangle::canvasPressEvent( QMouseEvent *e )
{
	Q_UNUSED( e );
	_selectRect.setRect( 0, 0, 0, 0 );
	_rubberBand = new RubberBand( canvas(), true );
	_rubberBand->setColor(MapControlConfig::getInstance()->getSelectRubberBandColor());

}


void MapToolSelectRectangle::canvasMoveEvent( QMouseEvent *e )
{
	if ( e->buttons() != Qt::LeftButton )
		return;

	if ( !_dragging )
	{
		_dragging = true;
		_selectRect.setTopLeft( e->pos() );
	}
	_selectRect.setBottomRight( e->pos() );
	setRubberBand(canvas(), _selectRect, _rubberBand);
}


void MapToolSelectRectangle::canvasReleaseEvent( QMouseEvent *)
{  
	if ( _dragging )
	{
		// Set valid values for rectangle's width and height
		if ( _selectRect.width() == 1 )
		{
			_selectRect.setLeft( _selectRect.left() + 1 );
		}
		if ( _selectRect.height() == 1 )
		{
			_selectRect.setBottom( _selectRect.bottom() + 1 );
		}
	}

	if ( _rubberBand )
	{
		setRubberBand(canvas(), _selectRect, _rubberBand);
		canvas()->setSelectPolygon(_rubberBand->getPolygon());
		_rubberBand->reset( true );
		delete _rubberBand;
		_rubberBand = nullptr;
	}

	_dragging = false;
}

void MapToolSelectRectangle::setRubberBand( MapCanvas* canvas, QRect& selectRect,RubberBand* rubberBand )
{
	const MapToPixel* transform = canvas->getCoordinateTransform();

	auto ll = transform->screenToMap( selectRect.left(), selectRect.bottom());
	auto ur = transform->screenToMap(selectRect.right(), selectRect.top());


	if ( rubberBand )
	{
		rubberBand->reset( true );
		rubberBand->addPoint( ll, false );
		rubberBand->addPoint( Point( ur.getX(), ll.getY() ), false );
		rubberBand->addPoint( ur, false );
		rubberBand->addPoint( Point( ll.getX(), ur.getY() ), true );
	}
}




}//MapControl
}//TGS